package com.atguigu.gulimail.interceptor;

import com.atguigu.common.constant.CartConstant;
import com.atguigu.common.vo.MemberRespVo;
import com.atguigu.gulimail.vo.userInfoTo;
import org.apache.commons.lang.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.UUID;

/**
 * @author fangy
 * @date 2022-10-12 11:08
 */
public class CartInterceptor implements HandlerInterceptor {


    public static ThreadLocal<userInfoTo> threadLocal = new ThreadLocal<userInfoTo>();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        userInfoTo userInfoTo = new userInfoTo();

        MemberRespVo attribute = (MemberRespVo) request.getSession().getAttribute("loginUser");
        if(attribute != null){
            userInfoTo.setUserId(attribute.getId());
        }

        Cookie[] cookies = request.getCookies();
        //不管是什么操作，只要是取一个可能为null的值，都要判断
        if(cookies != null && cookies.length > 0){
            for (Cookie cookie : cookies) {
                if (cookie.getName().equals(CartConstant.TEMP_USER_COOKIE_NAME)){
                    userInfoTo.setUserKey(cookie.getValue());
                    userInfoTo.setTempUser(true);
                }
            }
        }
        if(StringUtils.isEmpty(userInfoTo.getUserKey())){
            String s = UUID.randomUUID().toString();
            String replace = s.replace("-", "");

            userInfoTo.setUserKey(replace);
        }

        threadLocal.set(userInfoTo);

        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

        userInfoTo info = threadLocal.get();

        if(!info.isTempUser()){

            Cookie cookie = new Cookie("user-key", info.getUserKey());


            cookie.setDomain("gulimall.com");
            cookie.setPath("/");
            cookie.setHttpOnly(true);


            response.addCookie(cookie);
        }

        threadLocal.remove();

    }
}
